﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using cecbData;
using cecbClasses;
using cecbClasses.Data_Classes;
using cecbClasses.Data_Adapters;
using System.Data;
using cecbClasses.Data_Adapters.Project;
namespace CECB.Project
{
    /// <summary>
    /// Interaction logic for UpdateProj_BasicDtails.xaml
    /// </summary>
    public partial class UpdateProj_BasicDtails : Window
    {
        List<ProjTyMParams> MainParamList = new List<ProjTyMParams>();
        List<ProjTyMParams> SelectedMainParamList = new List<ProjTyMParams>();
        //List<Data_ProjectSubParameter> oSubParamList = new List<Data_ProjectSubParameter>();


        private bool stopRefreshControls = false;
        private bool dataChanged = false;

        string destFile;
        string destFile1;

        string updestfile;
        string upModeldestFile;

        Func_Projects ObjProjctsFunc = new Func_Projects();
        List<Data_ProjectGridLocation> listObjGrdLoc = new List<Data_ProjectGridLocation>();
        List<Data_ProjectSubParameter> oSubParamList = new List<Data_ProjectSubParameter>();


        public UpdateProj_BasicDtails()
        {
            InitializeComponent();
            ProjctNameAutocompleteTextBox.ItemsSource = ObjProjctsFunc.GetAllRegProjNames();
        }

        private void button_catgryAdd_Click(object sender, RoutedEventArgs e)
        {
            //ProjectCatogry winProjCat = new ProjectCatogry();
            //winProjCat.ShowDialog();
        }

        private void button_projTypeAdd_Click(object sender, RoutedEventArgs e)
        {
            ProjectTypes winProjTYpes = new ProjectTypes();
            winProjTYpes.ShowDialog();

        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {

        }


        private bool ValidateData()
        {
            bool isValid = false;

            if (string.IsNullOrEmpty(ProjctNameAutocompleteTextBox.Text))
            {
                MessageBox.Show("Please Enter Project Name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

            }
            else if ((string.IsNullOrEmpty(comboBox_ProjectCatogry.Text)) || (comboBox_ProjectCatogry.SelectedIndex < 0))
            {
                MessageBox.Show("Please Select Project Catogry", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            else if ((string.IsNullOrEmpty(comboBox_projectType.Text)) || ((comboBox_projectType.SelectedIndex < 0)))
            {
                MessageBox.Show("Please Selcet Project Type", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else if (string.IsNullOrEmpty(textBox_client.Text))
            {
                MessageBox.Show("Please Enter Project Client", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            //else if (string.IsNullOrEmpty(lblConsultent.Content))
            //{

            //    MessageBox.Show("Please Select Project Consultent", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

            //}
            else if (string.IsNullOrEmpty(textBox_appAgency.Text))
            {
                MessageBox.Show("Please Enter Project Agency", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

            }
            else if (string.IsNullOrEmpty(textBox_location.Text))
            {
                MessageBox.Show("Please Enter Project Location", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            //else if (listObjGrdLoc.Count() == 0)
            //{
            //    MessageBox.Show("Please Enter Grid Location", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            //}
            //else if (listObjGrdLoc.Count() < 3)
            //{
            //    MessageBox.Show("Please enter atleast 3 Grid Locations", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            //}
            else if (ValidateGridLocations() == false)
            {
                MessageBox.Show("Invalid Grid Location ", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                isValid = true;
            }

            return isValid;

        }

        private bool ValidateGridLocations()
        {
            bool isValid = true;

            foreach (Data_ProjectGridLocation oGridLoc in listObjGrdLoc)
            {

                if (((oGridLoc.Loc_latitude == null) && (oGridLoc.Loc_longitude == null)) || ((oGridLoc.Loc_latitude == "") && (oGridLoc.Loc_longitude == "")))
                {
                    continue;
                }

                if ((oGridLoc.Loc_latitude == null) || (oGridLoc.Loc_longitude == null) || (oGridLoc.Loc_latitude == "") || (oGridLoc.Loc_longitude == ""))
                {
                    isValid = false;
                    return isValid;
                }
            }

            return isValid;
        }


        private void button_projUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                if (ValidateData() == false)
                    return;
                else
                {

                    Data_Projects ObjProjcts = new Data_Projects();
                    ObjProjcts.Proj_reference = labelProjRef.Content.ToString(); ;
                    ObjProjcts.Proj_name = ProjctNameAutocompleteTextBox.Text;
                    ObjProjcts.Proj_category = comboBox_ProjectCatogry.SelectedValue.ToString();
                    ObjProjcts.Proj_type = comboBox_projectType.SelectedValue.ToString();
                    ObjProjcts.Proj_location = textBox_location.Text;
                    ObjProjcts.Proj_consultant = textBox_consltnt.Text;
                    ObjProjcts.Proj_proponent = textBox_client.Text;
                    ObjProjcts.Proj_approvingAgency = textBox_appAgency.Text;
                    ObjProjcts.Proj_otherDetails = tbMultiLine.Text;
                    ObjProjcts.Proj_modelImage = destFile1;
                    ObjProjcts.Proj_planImage = destFile;
                    ObjProjcts.Proj_status = true;

                    //restore current image while updating

                    Data_Projects ObjProj = new Data_Projects();
                    ObjProj.Proj_reference = labelProjRef.Content.ToString(); ;
                    Projects selectedPrj = ObjProjctsFunc.GetProjectByCode(ObjProj);


                    if (ObjProjcts.Proj_modelImage == null && ObjProjcts.Proj_planImage == null)
                    {

                        upModeldestFile = selectedPrj.proj_modelImage;
                        ObjProjcts.Proj_modelImage = upModeldestFile;


                        updestfile = selectedPrj.proj_planImage;
                        ObjProjcts.Proj_planImage = updestfile;

                    }
                    else if (ObjProjcts.Proj_modelImage == null)
                    {

                        upModeldestFile = selectedPrj.proj_modelImage;
                        ObjProjcts.Proj_modelImage = upModeldestFile;

                        ObjProjcts.Proj_planImage = destFile;

                    }

                    else if (ObjProjcts.Proj_planImage == null)
                    {
                        updestfile = selectedPrj.proj_planImage;
                        ObjProjcts.Proj_planImage = updestfile;

                        ObjProjcts.Proj_modelImage = destFile1;

                    }

                    else
                    {
                        ObjProjcts.Proj_modelImage = destFile1;
                        ObjProjcts.Proj_planImage = destFile;
                    }

                    //  ObjProjctsFunc.UpdateProjects(ObjProjcts, listObjGrdLoc, oSubParamList);




                    if (ObjProjctsFunc.UpdateProjects(ObjProjcts, listObjGrdLoc, oSubParamList) == true)
                    {
                        //restore changes in opened autocomplete
                        ProjctNameAutocompleteTextBox.ItemsSource = ObjProjctsFunc.GetAllRegProjNames();


                        MessageBox.Show("Project Updated Successfully", "CECB", MessageBoxButton.OK, MessageBoxImage.Information);
                        ProjctNameAutocompleteTextBox.Text = "";

                        ClearData();

                    }
                    else
                    {
                        MessageBox.Show("Project Updation Failed", "CECB", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch
            {
                MessageBox.Show("Please select a Project!", "CECB", MessageBoxButton.OK, MessageBoxImage.Warning);
            }


        }


        private void ClearData()
        {
            labelProjRef.Content = "";
            //  ProjctNameAutocompleteTextBox.Text = "";
            comboBox_ProjectCatogry.SelectedIndex = -1;
            comboBox_projectType.SelectedIndex = -1;
            textBox_appAgency.Text = "";
            textBox_client.Text = "";
            // combobox_TeamLeader.SelectedIndex = -1;
            textBox_consltnt.Text = "";
            textBox_location.Text = "";
            ProjctNameAutocompleteTextBox.Focus();
            listView1.Items.Clear();
            listObjGrdLoc.Clear();
            textBox_latitude.Text = "";
            textBox_longitude.Text = "";
            image_plan.Source = null;
            image_model.Source = null;
            tbMultiLine.Text = "";
            listBoxMainParam.Items.Clear();
            listBoxSelMainParam.Items.Clear();
            dataGridSubParameter.ItemsSource = null; 
        }

        private void GetSelectList(List<Data_ProjectSubParameter> sParam)
        {
            var queryList = ((from d in sParam
                              select d.Mparam_reference).Distinct());

            SelectedMainParamList.Clear();
            listBoxSelMainParam.Items.Clear();

            foreach (var oSubParam in queryList.ToList())
            {
                var sel = (from a in MainParamList
                           where a.mparam_reference == oSubParam.ToString()
                           select a).Single();

                SelectedMainParamList.Add(sel);
                MainParamList.Remove(sel);
                FillMainParameters();
                FillSelectedMainParam();

            }
        }

        private void ReferenceTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            listView1.Items.Clear();
            try
            {
                Data_Projects ObjProj1 = new Data_Projects();
                ObjProj1.Proj_name = ProjctNameAutocompleteTextBox.Text;

                Projects selectedPrj = ObjProjctsFunc.GetProjectByName(ObjProj1);
                labelProjRef.Content = selectedPrj.proj_reference;
                ObjProj1.Proj_reference = labelProjRef.Content.ToString();
                //   Projects selectedPrj = ObjProjctsFunc.GetProjectByCode(ObjProj1);


                //Projects selectProjRef = ObjProjctsFunc.GetProjectByName(ObjProj1);
                //labelProjRef.Content = selectProjRef.proj_reference;
                //ObjProj1.Proj_reference = labelProjRef.Content.ToString();
                //Projects selectedPrj = ObjProjctsFunc.GetProjectByCode(ObjProj1);


                if (ObjProj1.Proj_reference != "")
                {
                    //textBox_PrjectName.Text = selectedPrj.proj_name;

                    FillPrjCategories();
                    textBox_location.Text = selectedPrj.proj_location;
                    comboBox_ProjectCatogry.SelectedValue = selectedPrj.proj_category;
                    comboBox_projectType.SelectedValue = selectedPrj.proj_type;
                    textBox_client.Text = selectedPrj.proj_proponent;
                    textBox_consltnt.Text = selectedPrj.proj_consultant;
                    textBox_appAgency.Text = selectedPrj.proj_approvingAgency;
                    tbMultiLine.Text = selectedPrj.proj_otherDetails;

                    ShowData(labelProjRef.Content.ToString());

                    updestfile = selectedPrj.proj_planImage;
                    upModeldestFile = selectedPrj.proj_modelImage;

                    //--- Display Parameter List ---
                    oSubParamList = ObjProjctsFunc.GetSubParameterList(ObjProj1.Proj_reference);

                    GetSelectList(oSubParamList);
                    dataGridSubParameter.ItemsSource = oSubParamList;


                    // --- Display Images ---
                    if (updestfile == null && upModeldestFile == null)
                    {
                        label_ImagePlanInfo.Content = "Images not found".ToString();
                        image_model.Visibility = System.Windows.Visibility.Hidden;
                        image_plan.Visibility = System.Windows.Visibility.Hidden;
                    }
                    else if (updestfile == null)
                    {
                        image_plan.Visibility = System.Windows.Visibility.Hidden;
                        label_ImagePlanInfo.Content = "Image Plan not found".ToString();
                        image_model.Visibility = System.Windows.Visibility.Visible;
                        image_model.Source = new BitmapImage(new Uri(upModeldestFile));
                    }
                    else if (upModeldestFile == null)
                    {
                        image_model.Visibility = System.Windows.Visibility.Hidden;
                        labelModelImg.Content = "Image Model not Found".ToString();
                        image_plan.Visibility = System.Windows.Visibility.Visible;
                        image_plan.Source = new BitmapImage(new Uri(updestfile));
                    }
                    else
                    {
                        label_ImagePlanInfo.Content = "".ToString();
                        labelModelImg.Content = "".ToString();
                        image_plan.Visibility = System.Windows.Visibility.Visible;
                        image_model.Visibility = System.Windows.Visibility.Visible;
                        image_plan.Source = new BitmapImage(new Uri(updestfile));
                        image_model.Source = new BitmapImage(new Uri(upModeldestFile));
                    }
                }
                else
                {

                    // --- Clear Dtls --
                    ClearData();

                }
            }
            catch
            {
                label_ImagePlanInfo.Content = "Image Plan Not Found";

            }


        }



        private void button_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            FillPrjCategories();
            FillPrjType();



        }




        public void FillPrjCategories()
        {

            List<Categories> CatgryList = ObjProjctsFunc.GetAllCatogries();
            comboBox_ProjectCatogry.ItemsSource = CatgryList;
        }


        public void FillPrjType()
        {

            List<cecbData.ProjectTypes> ProjectTypeList = ObjProjctsFunc.GetAllProjectTypes();
            comboBox_projectType.ItemsSource = ProjectTypeList; ;
        }

        private void button_projdelete_Click(object sender, RoutedEventArgs e)
        {

            if (ProjctNameAutocompleteTextBox.Text == "")
            {
                MessageBox.Show("Please select a Project");
            }
            else
            {
                if (MessageBox.Show("Are You sure you want to Delete this Project Data", "Delete Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    bool isDeleted = false;

                    Data_Projects clsProj = new Data_Projects();
                    clsProj.Proj_reference = labelProjRef.Content.ToString();
                    isDeleted = ObjProjctsFunc.DeleteProjects(clsProj);
                    if (isDeleted == true)
                    {

                        MessageBox.Show("Project Deleted Successfully", "Project", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBox.Show("Project Deletion Failed", "Project", MessageBoxButton.OK, MessageBoxImage.Warning);

                    }
                }
            }
        }



        private void button_UpdatePlanImage_Click(object sender, RoutedEventArgs e)
        {
            image_plan.Visibility = System.Windows.Visibility.Visible;

            // Create OpenFileDialog 

            Microsoft.Win32.OpenFileDialog dlg1 = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 

            dlg1.DefaultExt = ".jpg";

            dlg1.Filter = "JPG files (*.jpg)|*.jpg|All files (*.*)|*.*";



            // Display OpenFileDialog by calling ShowDialog method 

            Nullable<bool> result = dlg1.ShowDialog();



            // Get the selected file name and display in a TextBox 

            if (result == true)
            {

                // Open document 
                string filename = dlg1.FileName;

                string targetPath = System.IO.Directory.GetCurrentDirectory().ToString();
                targetPath = targetPath + "\\Project_PlanImages_Prj1";


                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                // Use Path class to manipulate file and directory paths. 
                string sourceFile = System.IO.Path.GetFileName(filename);

                destFile = System.IO.Path.Combine(targetPath, sourceFile);

                if (System.IO.File.Exists(destFile) == false)
                {
                    System.IO.File.Copy(filename, destFile, true);
                }

                image_plan.Source = new BitmapImage(new Uri(destFile));
                label_ImagePlanInfo.Content = sourceFile;


            }
        }



        private void button_updateModelImage_Click(object sender, RoutedEventArgs e)
        {
            image_model.Visibility = System.Windows.Visibility.Visible;

            // Create OpenFileDialog 

            Microsoft.Win32.OpenFileDialog dlg1 = new Microsoft.Win32.OpenFileDialog();



            // Set filter for file extension and default file extension 

            dlg1.DefaultExt = ".jpg";

            dlg1.Filter = "JPG files (*.jpg)|*.jpg|All files (*.*)|*.*";



            // Display OpenFileDialog by calling ShowDialog method 

            Nullable<bool> result = dlg1.ShowDialog();



            // Get the selected file name and display in a TextBox 

            if (result == true)
            {

                // Open document 
                string filename = dlg1.FileName;

                string targetPath = System.IO.Directory.GetCurrentDirectory().ToString();
                targetPath = targetPath + "\\Project_PlanImages_Prj1";


                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                // Use Path class to manipulate file and directory paths. 
                string sourceFile = System.IO.Path.GetFileName(filename);

                destFile1 = System.IO.Path.Combine(targetPath, sourceFile);

                if (System.IO.File.Exists(destFile1) == false)
                {
                    System.IO.File.Copy(filename, destFile1, true);
                }

                // System.IO.File.Copy(filename, destFile1, true);

                image_model.Source = new BitmapImage(new Uri(destFile1));

                labelModelImg.Content = sourceFile;
            }



        }



        private void comboBox_ProjectCatogry_DropDownOpened(object sender, EventArgs e)
        {
            FillPrjCategories();
        }

        private void comboBox_projectType_DropDownOpened(object sender, EventArgs e)
        {
            FillPrjType();
        }



        private void Window_Loaded_2(object sender, RoutedEventArgs e)
        {


            FillPrjCategories();
            FillPrjType();


            if (listView1.Items.Count == 0)
            {
                AddRow();
            }
            else
            {
                listView1.SelectedIndex = 0;
            }
            setDataChanged(false);
            textBox_longitude.Focus();

        }


        private void ShowData(string gridProjref)
        {

            List<Project_AreaGrids> ListPrjGridDtls = ObjProjctsFunc.GetGridDtlsByRef(gridProjref);

            listView1.Items.Clear();
            listObjGrdLoc.Clear();
            foreach (Project_AreaGrids oPrjTypeDtls in ListPrjGridDtls)
            {
                Data_ProjectGridLocation oPrjTypes = new Data_ProjectGridLocation();
                oPrjTypes.Loc_latitude = oPrjTypeDtls.loc_latitude.ToString();
                oPrjTypes.Loc_longitude = oPrjTypeDtls.loc_longitude.ToString();

                listView1.Items.Add(oPrjTypes);
                listObjGrdLoc.Add(oPrjTypes);
            }


        }

        private void button_NewRecord_Click(object sender, RoutedEventArgs e)
        {
            setDataChanged(true);
            AddRow();
        }

        private void setDataChanged(bool value)
        {
            dataChanged = value;

        }

        private void AddRow()
        {
            Data_ProjectGridLocation oLoc = new Data_ProjectGridLocation();
            oLoc.Grid_id = listView1.Items.Count + 1;

            listObjGrdLoc.Add(oLoc);

            listView1.Items.Add(new Data_ProjectGridLocation("", ""));
            listView1.SelectedIndex = listView1.Items.Count - 1;

            textBox_latitude.Text = "";
            textBox_longitude.Text = "";
            textBox_longitude.Focus();
        }


        private void textBox_longitude_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshListView(textBox_longitude.Text, textBox_latitude.Text);
        }

        private void textBox_latitude_TextChanged(object sender, TextChangedEventArgs e)
        {
            RefreshListView(textBox_longitude.Text, textBox_latitude.Text);
        }

        private void RefreshListView(string value1, string value2)
        {
            Data_ProjectGridLocation lvc = (Data_ProjectGridLocation)listView1.SelectedItem; //new ListViewClass(value1, value2);
            if (lvc != null && !stopRefreshControls)
            {
                setDataChanged(true);
                var query = from t in listObjGrdLoc
                            where t.Grid_id == listView1.SelectedIndex + 1
                            select t;

                if (query.Count() > 0)
                {
                    query.Single().Loc_latitude = value1;
                    query.Single().Loc_longitude = value2;
                }

                if (value1 != "")
                {
                    lvc.Loc_longitude = value1;
                }

                if (value2 != "")
                {
                    lvc.Loc_latitude = value2;
                }
                listView1.Items.Refresh();
            }


        }
        private void textBox_longitude_GotFocus(object sender, RoutedEventArgs e)
        {
            StoreCurrentValue(sender);
            textBox_latitude.SelectAll();

        }

        private void textBox_latitude_GotFocus(object sender, RoutedEventArgs e)
        {

            StoreCurrentValue(sender);
            textBox_longitude.SelectAll();
        }

        private void StoreCurrentValue(object sender)
        {
            TextBox myText = (TextBox)sender;
            myText.Tag = myText.Text;
        }

        private void textBox_longitude_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                RestoreOldValue(sender);
            }

        }



        private void textBox_latitude_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                RestoreOldValue(sender);
            }
        }
        private void RestoreOldValue(object sender)
        {
            TextBox myText = (TextBox)sender;

            if (myText.Text != myText.Tag.ToString())
            {
                myText.Text = myText.Tag.ToString();
                myText.SelectAll();
            }
        }

        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Data_ProjectGridLocation lvc = (Data_ProjectGridLocation)listView1.SelectedItem;
            if (lvc != null)
            {
                stopRefreshControls = true;
                textBox_longitude.Text = lvc.Loc_longitude;
                textBox_latitude.Text = lvc.Loc_latitude;
                stopRefreshControls = false;



            }

        }


        private void button_RemoveRecord_Click(object sender, RoutedEventArgs e)
        {
            setDataChanged(true);
            int selectedIndex = listView1.SelectedIndex;



            Project_AreaGrids ObjGrd1 = new Project_AreaGrids();
            listObjGrdLoc.RemoveAt(listView1.SelectedIndex);
            listView1.Items.Remove(listView1.SelectedItem);

            // if no rows left, add a blank row
            if (listView1.Items.Count == 0)
            {
                AddRow();
            }
            else if (selectedIndex <= listView1.Items.Count) // otherwise select next row
            {
                listView1.SelectedIndex = selectedIndex;

            }
            else // not above cases? Select last row
            {
                listView1.SelectedIndex = listView1.Items.Count - 1;

            }
        }


        public void GetMainParameters()
        {
            MainParamList = ObjProjctsFunc.getAllMainParamerter();

            FillMainParameters();
        }




        private void buttonvwMap_Click(object sender, RoutedEventArgs e)
        {
            ViewMap_Window vp = new ViewMap_Window();
            vp.Show();
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void ButtonVwMap_Click_1(object sender, RoutedEventArgs e)
        {
            ViewMap_Window vmow = new ViewMap_Window();
            vmow.Show();
        }

        private void comboBox_projectType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetMainParameters();
        }

        private void buttonMParAddAll_Click(object sender, RoutedEventArgs e)
        {
            SelectedMainParamList.Clear();
            listBoxSelMainParam.Items.Clear();

            listBoxMainParam.Items.Clear();

            SelectedMainParamList.AddRange(MainParamList);
            FillSelectedMainParam();

            MainParamList.Clear();
            FillMainParameters();




        }

        public void FillMainParameters()
        {
            listBoxMainParam.Items.Clear();

            foreach (ProjTyMParams mParam in MainParamList)
            {
                listBoxMainParam.Items.Add(mParam);
            }
        }

        private void buttonMParAdd_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxMainParam.SelectedItems.Count > 0)
            {
                var sel = (from a in MainParamList
                           where a.mparam_reference == listBoxMainParam.SelectedValue.ToString()
                           select a).Single();

                SelectedMainParamList.Add(sel);
                MainParamList.Remove(sel);
                FillMainParameters();
                FillSelectedMainParam();
            }
        }

        private void FillSelectedMainParam()
        {

            listBoxSelMainParam.Items.Clear();

            foreach (ProjTyMParams Mparam in SelectedMainParamList)
            {
                listBoxSelMainParam.Items.Add(Mparam);
            }
        }

        private void buttonMParRemove_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxSelMainParam.SelectedItems.Count > 0)
            {
                var sel = (from a in SelectedMainParamList
                           where a.mparam_reference == listBoxSelMainParam.SelectedValue.ToString()
                           select a).Single();

                SelectedMainParamList.Remove(sel);
                MainParamList.Add(sel);
                FillSelectedMainParam();
                FillMainParameters();
            }
        }

        private void buttonMParRemoveAll_Click(object sender, RoutedEventArgs e)
        {

            MainParamList.AddRange(SelectedMainParamList);



            SelectedMainParamList.Clear();
            FillSelectedMainParam();

            FillMainParameters();
        }

        private void buttonMParaConfirm_Click(object sender, RoutedEventArgs e)
        {
            //--- Add Main Parameter
            foreach (ProjTyMParams mParam in SelectedMainParamList)
            {
                var isExists = (from d in oSubParamList
                                where d.Mparam_reference == mParam.mparam_reference
                                select d).Count();

                if (isExists == 0)
                {
                    List<ProjTySubParams> sParamList = ObjProjctsFunc.getAllSubParamerter(mParam.mparam_reference);

                    foreach (ProjTySubParams sPm in sParamList)
                    {
                        Data_ProjectSubParameter oSubParam = new Data_ProjectSubParameter();

                        oSubParam.Ptype_reference = comboBox_projectType.SelectedValue.ToString();
                        oSubParam.Mparam_reference = mParam.mparam_reference;
                        oSubParam.Mparam_name = mParam.mparam_name;
                        oSubParam.SubPrm_ref = sPm.subPrm_ref;
                        oSubParam.SubPrm_name = sPm.subPrm_name;

                        oSubParam.SubPrm_value = "";

                        oSubParamList.Add(oSubParam);
                    }
                }
            }

            // Remove Saved Parameters
            oSubParamList = (from t in oSubParamList
                             where (SelectedMainParamList.Any(mRef => mRef.mparam_name == t.Mparam_name))
                             select t).ToList();

            dataGridSubParameter.ItemsSource = null;
            dataGridSubParameter.ItemsSource = oSubParamList;
        }

        private void button_CustomizeParmDetails_Click(object sender, RoutedEventArgs e)
        {
            Project.PrjctType_ParamDetails oPRojTypeWin = new PrjctType_ParamDetails();
            oPRojTypeWin.Show();
        }

        private void Image_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

    }

}

